﻿using System;
using System.Collections.Generic;
using System.Linq;
using Dexter.Core.Data.Repository;
using Dexter.Domain.Model;
using Dexter.Domain.Results;
using Dexter.Logger.Contracts;
using Dexter.Repository.NHibernate.Queries;
using NHibernate;
using Topics.Radical.Validation;
using ISessionFactory = Dexter.Repository.NHibernate.SessionFactory.ISessionFactory;

namespace Dexter.Repository.NHibernate.Repositories {
	/// <summary>
	/// The implementation of <see cref="IInboxRepository"/>
	/// </summary>
	/// <example>The following is an example of initializing 
	///          an <c>InboxRepository</c> type:
	///   <code>
	///       // Create the type.
	///       InboxRepository ds = new InboxRepository;
	/// 
	///       if ( null == ds )
	///           return;
	/// 
	///       return ds.DoSomething( 5 );
	///   </code>
	/// </example>
	public class InboxRepository : RepositoryBase<InboxMessage>, IInboxRepository {
		/// <summary>
		/// Initializes a new instance of the <see cref="InboxRepository"/> class.
		/// </summary>
		/// <param name="sessionFactory">The session factory.</param>
		/// <param name="logger">The logger.</param>
		public InboxRepository ( ISessionFactory sessionFactory , ILogger logger ) : base ( sessionFactory , logger ) {}

		/// <summary>
		/// Deletes the specified <see cref="InboxMessage"/> from the repository.
		/// </summary>
		/// <param name="item">The inbox message.</param>
		/// <exception cref="ArgumentNullException">If <paramref name="item"/> is <c>null</c>.</exception>
		public void Delete ( InboxMessage item ) {
			Ensure.That ( item )
				.Named ( "item" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsNotNull ( )
				.WithMessage ( "Invalid inbox message" );

			item.ValidateForSave (  );

			Session.Save ( item );
		}

		/// <summary>
		/// 	Saves the specified <see cref="InboxMessage"/> into the repository.
		/// </summary>
		/// <param name="item">The inbox message.</param>
		/// <exception cref="ArgumentNullException">If <paramref name="item"/> is <c>null</c>.</exception>
		public void Save ( InboxMessage item ) {
			Ensure.That ( item )
				.Named ( "item" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsNotNull ( )
				.WithMessage ( "Invalid inbox message" );

			item.ValidateForSave (  );

			Session.Save ( item );
		}

		///<summary>
		///	Return a list of <see cref="InboxMessage"/> sorted by creation date.
		///</summary>
		///<param name = "pageIndex">Index of the page (0 based).</param>
		///<param name = "pageSize">The number of items to retrieve.</param>
		/// <param name = "enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		///<returns>An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.</returns>
		///<exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		///<exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public IPagedResult <InboxMessage> GetList ( int pageIndex , int pageSize , bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsGreaterThen ( 0, Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );

			IFutureValue<long> total = Session.GetNamedQuery ( KnownQueries.InboxRepository.GetListCount )
				.FutureValue<long> ( );

			IEnumerable<InboxMessage> result = Session.GetNamedQuery ( KnownQueries.InboxRepository.GetListOrdedByMessageDate )
				.SetFirstResult ( pageIndex * pageSize )
				.SetMaxResults ( pageSize )
				.SetReadOnly ( !enableTracking )
				.Future<InboxMessage> ( );

			return new PagedResult<InboxMessage> ( pageIndex, pageSize, result.ToList ( ), total.Value );
		}
	}
}
